package com.daxin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxin.mapper.UserMapper;
import com.daxin.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass).setStatus(1);
        userMapper.insert(user);
    }

    @Override
    @Transactional
    public String findUserByUP(User user) {
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        QueryWrapper queryWrapper = new QueryWrapper(user);
        User userDB = userMapper.selectOne(queryWrapper);

        String token = UUID.randomUUID().toString().replace("-", "");
        return userDB==null?null:token;
    }

    @Override
    @Transactional
    public User findUserById(String id) {
        User user = userMapper.selectById(id);
        return user;

    }

    @Override
    @Transactional
    public User findUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    @Override
    @Transactional
    public User findUserByTel(String tel) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tel", tel);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
}
